<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2021/4/15
 * Time: 18:16
 */
namespace Io\Pcntl;

class Worker
{
    // 接收
    public $onReceive = null;
    // 链接
    public $onConnect = null;

    public $onClose   = null;

    public $socket    = null;

    protected $config = [
        'worker_num' => 4,
    ];

    public function __construct($socket_address)
    {
        $this->socket = stream_socket_server($socket_address);
        stream_set_blocking($this->socket, 0);
        echo $socket_address.PHP_EOL;
    }

    public function index()
    {
        echo '111';
    }

    // 接收和链接处理事
    public function accept()
    {
        while (true) {
            $client = @stream_socket_accept($this->socket);
            if (is_callable($this->onConnect)) {
                // 执行函数
                ($this->onConnect)($this);
            }
            $buffer = '';
            $data = fread($client, 65535);
            if (is_callable($this->onReceive)) {
                // 执行函数
                ($this->onReceive)($this, $client, $data);
            }

            var_dump($buffer);
            fwrite($client,'server hellow');
            fclose($client);
            var_dump($client);
        }
    }

    public function start()
    {
        // 启动服务
        //$this->accept();
        $this->fork();
    }
    // 创建多个子进程， 并且让子进程运行accept
    public function fork()
    {
        for ($i = 0; $i < $this->config['worker_num']; $i++ ) {
            $son11 = pcntl_fork();
            if ($son11 > 0) {
                echo posix_getpid().PHP_EOL;
            } else if ($son11 < 0) {

            } else {
                echo posix_getpid().PHP_EOL;
                echo $son11.": i".PHP_EOL;
                // 子进程  处理请求接收
                $this->accept();
                //break;
                exit;
            }

        }

        if ($son11 > 0) {
            $status = 0;
            pcntl_wait($status);

        }
    }

    public function send($conn, $data)
    {
        fwrite($conn, $data);
    }
}